package com.example.xiaosen.controller;

import com.example.xiaosen.entity.vo.MessageVO;
import com.example.xiaosen.repository.ChatHistoryRepository;
import com.example.xiaosen.tools.CourseTools;
import com.example.xiaosen.tools.DateTimeTools;
import io.modelcontextprotocol.client.McpAsyncClient;
import io.modelcontextprotocol.client.McpSyncClient;
import io.modelcontextprotocol.spec.McpSchema;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.content.Media;
import org.springframework.ai.mcp.AsyncMcpToolCallbackProvider;
import org.springframework.ai.mcp.SyncMcpToolCallbackProvider;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MimeType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: zhouxj@ferrotec.com.cn
 * @version: v1.0
 * @Date: 2025/5/8 14:18
 * @Description:
 */
@CrossOrigin("*")
@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
public class ChatController {

    private final List<McpSyncClient> mcpSyncClients;
    private final ChatClient chatClient;

    private final DateTimeTools dateTimeTools;
    private final ChatHistoryRepository chatHistoryRepository;

    @GetMapping("generate")
    public String generate(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        return chatClient.prompt(message).tools(dateTimeTools).call().content();
    }

    @RequestMapping(value = "/chat", produces = "text/html;charset=utf-8")
    public Flux<String> chat(
            @RequestParam("prompt") String prompt,
            @RequestParam("chatId") String chatId,
            @RequestParam(value = "files", required = false)
            List<MultipartFile> files) {
        // 1.保存会话id
        chatHistoryRepository.save("chat", chatId);
        // 2.请求模型
        if (files == null || files.isEmpty()) {
            // 没有附件，纯文本聊天
            return textChat(prompt, chatId);
        } else {
            // 有附件，多模态聊天
            return multiModalChat(prompt, chatId, files);
        }
    }

    private Flux<String> multiModalChat(String prompt, String chatId,
                                        List<MultipartFile> files) {
        // 1.解析多媒体
        List<Media> medias = files.stream()
                .map(file -> new Media(

                                MimeType.valueOf(Objects.requireNonNull(file.getContentType())),
                                file.getResource()
                        )
                )
                .toList();
        // 2.请求模型
        return chatClient.prompt()
                .user(p ->
                        p.text(prompt).media(medias.toArray(Media[]::new)))
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID,
                        chatId))
                .stream()
                .content();
    }
    private Flux<String> textChat(String prompt, String chatId) {
        // MCP客户端融合到springAi
        SyncMcpToolCallbackProvider syncMcpToolCallbackProvider = new SyncMcpToolCallbackProvider(mcpSyncClients);
        // 获取MCP工具回调列表
        ToolCallback[] toolCallbacks = syncMcpToolCallbackProvider.getToolCallbacks();
        return chatClient.prompt()
                .user(prompt)
                .toolCallbacks(syncMcpToolCallbackProvider)
                // 会话记忆id
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID,
                        chatId))
                .stream()
                .content();
    }
}
